import subprocess
import os

"""
编译并上传本地文件夹到OSS
"""
# 判断当前使用的node版本是否为16.16.0,如果不是，则切换
current_node_version = subprocess.run(["node", "--version"], capture_output=True, text=True)
if current_node_version.stdout.strip() != "v16.16.0":
    subprocess.run(["nvm", "use", "16.16.0"])
# 编译vuepress
subprocess.run(["npm", "run", "docs:build"])
# 定义本地文件夹路径
local_folder = ".vuepress/dist"
# 定义OSS路径
oss_folder = "oss://jjbiji/"

# 检查本地文件夹是否存在
if not os.path.isdir(local_folder):
    print("Error: Local folder does not exist.")
    exit(1)

# 准备ossutil cp命令
# 如果操作系统是 linux，则用 ossutil64，如果是MacOS，则用 ossutil，如果是Windows，则用 ossutil.exe
if os.name == 'posix':
    # 区分 Linux 和MacOS
    if os.uname().sysname == 'Darwin':
        command = ['ossutil', 'cp', '-r', '-f', local_folder, oss_folder]
    else:
        command = ['ossutil64', 'cp', '-r', '-f', local_folder, oss_folder]
elif os.name == 'nt':
    command = ['ossutil.exe', 'cp', '-r', '-f', local_folder, oss_folder]
else:
    print("Error: Unsupported operating system.")
    exit(1)

try:
    # 执行ossutil cp命令
    result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # 输出执行结果
    print(result.stdout.decode())
except subprocess.CalledProcessError as e:
    # 如果上传失败，输出错误信息
    print("Upload failed with error:", e.stderr.decode())
    exit(1)

print("Upload completed successfully.")